#!/usr/local/bin/perl
# leeym@leeym.com
use FindBin qw($Script);
use Module::CoreList;
use Data::Dumper;
use Cwd;
use strict;

my $port = shift;
$port = getcwd if !$port;
chdir($port) || die "$Script: can't chdir($port): $!";
my $maintainer = `make -V MAINTAINER`;
chomp($maintainer);
my $PORTSDIR = $ENV{PORTSDIR} || '/usr/ports';
my @PERL_VER;
my $err = 0;
for my $perlport (<$PORTSDIR/lang/perl*>)
{
  open(F, "$perlport/Makefile") || die $!;
  while (<F>)
  {
    my $ver = $1 if /^PERL_VER=\s*(\S+)/;
    next if !$ver;
    push(@PERL_VER, $ver);
    last;
  }
  close(F);
}
for my $pv (@PERL_VER)
{
  my $lvl = level($pv);
  for my $type (qw(BUILD RUN))
  {
    my $list = `make -V ${type}_DEPENDS PERL_VERSION=$pv PERL_VER=$pv`;
    my @DEPENDS = split(/\s+/, $list);
    foreach my $depend (@DEPENDS)
    {
      next if !$depend;
      my ($dep, $dir, $tgt) = split(':', $depend);
      next if $dir =~ m{lang/perl};
      my $mod = $dep;
      my $ver = 0;
      if ($mod =~ m{(<|>)})
      {
        ($mod, $ver) = ($1, $2) if $mod =~ m{(\S+)>=?(\S+)};
        $mod =~ s{^p5-}{};
        $mod =~ s{-}{::}g;
      }
      else
      {
        $mod =~ s{.*$pv/}{};
        $mod =~ s{mach/}{};
        $mod =~ s{\.pm$}{};
        $mod =~ s{/}{::}g;
      }
      die $depend if !$mod;
      my $first = level(Module::CoreList->first_release($mod, $ver));
      my $p = $port;
      $p =~ s{$PORTSDIR/}{};

      #printf("$p: $type: $mod-$ver F:$first <=> L:$lvl\n");
      if ($first && $first <= $lvl)
      {
        print sprintf("$p: %s_DEPENDS: %s is in perl>=$first [$lvl] $maintainer\n",
          $type, $ver ? "$mod-$ver" : $mod);
        $err++;
      }
      if ($type eq 'RUN' && $p !~ m{p5-Test} && $mod =~ m{^Test::})
      {
        print sprintf("$p: RUN_DEPENDS: requires $mod for tests only? [$lvl] $maintainer\n");
	$err++;
      }
    }
  }
}
exit($err);

# END

sub level
{
  my $v = shift;
  return if !$v;
  my ($x, $y, $z) = ($1, $2, $3) if $v =~ m{(\d+)\.?0*([1-9]*)\.?0*([1-9]*)};
  return sprintf("%d%03d%02d", $x, $y, $z);
}
